package com.jiangjiang.eshop.order.schedule;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jiangjiang.eshop.common.help.DateHelper;
import com.jiangjiang.eshop.inventory.service.InventoryService;
import com.jiangjiang.eshop.order.dto.OrderInfoDTO;
import com.jiangjiang.eshop.order.service.OrderInfoService;
import com.jiangjiang.eshop.order.service.OrderItemService;
import com.jiangjiang.eshop.order.status.LoggedOrderStateManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName AutoCancelOrderTask
 * @Description TODO
 * @Author jhw
 * @Date 2021/8/24 22:20
 * @Version 1.0
 **/
@Slf4j
@Component
@Transactional(rollbackFor = Exception.class)
public class AutoCancelOrderTask {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private DateHelper dateHelper;
    @Autowired
    private LoggedOrderStateManager orderStateManager;
    @Autowired
    private InventoryService inventoryService;

    @Scheduled(fixedRate = 1 * 60 * 1000)
    public void execute() {
       try {
           // 查询出所有未支付的订单数据
           List<OrderInfoDTO> orders = orderInfoService.queryAllUnPayed();
           if(CollectionUtils.isEmpty(orders)){
               return;
           }
           for (OrderInfoDTO order : orders) {
               if(dateHelper.getCurrentDate().getTime() - order.getGmtCreate().getTime() <= 24 * 60 * 60 * 1000){
                   continue;
               }
               orderStateManager.cancel(order);
               inventoryService.informCancelOrderEvent(order);
           }



       }catch (Exception e){
           log.warn("AutoCancelOrderTask error",e);
       }

    }


}
